package net.lcqf.http.token;

import cn.hutool.core.util.StrUtil;
import net.lcqf.http.constants.Constants;
import net.lcqf.http.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户账号令牌组件
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 贯彻己道的云 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/2/10 14:30
 * // +----------------------------------------------------------------------
 */
@Component
public class TokenComponent {

    /** 最后60秒续期 */
    private static final Long EXPIRE_TIME = 60L;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取当前登录用户id
     * @return {@code Integer}
     */
    public Integer getUserId() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        String token = getToken(request);
        if (StrUtil.isEmpty(token)) { return null; }

        return redisUtil.get(getTokenKey(token));
    }

    /**
     * 退出登录
     * @param request HttpServletRequest
     */
    public void logout(HttpServletRequest request) {
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtil.delete(userKey);
        }
    }


    /**
     * 续期用户端 TOKEN
     * @param token 登录TOKEN
     * @return Boolean
     */
    public Boolean check(String token){
        Boolean exists = redisUtil.exists(getTokenKey(token));
        if(exists){
            // 永久缓存(-1) 建议不要使用永久缓存，内存足够大、服务器性能足够好，那就使劲造
            Long expire = redisUtil.getExpire(getTokenKey(token));
            if (expire != -1 && expire <= EXPIRE_TIME) {
                Integer uid = redisUtil.get(getTokenKey(token));
                redisUtil.set(getTokenKey(token), uid, Constants.TOKEN_EXPRESS_MINUTES, TimeUnit.MINUTES);
            }
        } else {
            exists = false;
        }
        return exists;
    }


    /**
     * 获取请求token
     * @param request HttpServletRequest
     * @return {@code String}
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(Constants.HEADER_AUTHORIZATION_KEY);
        if (StrUtil.isNotEmpty(token) && token.startsWith(Constants.USER_TOKEN_REDIS_KEY_PREFIX)) {
            token = token.replace(Constants.USER_TOKEN_REDIS_KEY_PREFIX, "");
        }
        return token;
    }
    private String getTokenKey(String uuid) {
        return Constants.USER_TOKEN_REDIS_KEY_PREFIX + uuid;
    }

}
